package demo.RiskPlatformInterface;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PostRequest {
    public static Logger LOG = LoggerFactory.getLogger(PostRequest.class);

    public static final String STATUSCODE = "statusCode";
    public static final String REQUESTIME = "requestTime";
    public static JSONObject execute(String URL, JSONObject param) {
//        JSONObject param = new JSONObject();
//        param.put("username", "dwrtd");
        if(URL == null || param == null) {
            LOG.error("input param null excep!!");
        }
        // 定义接收数据
        JSONObject result = new JSONObject();

        try {
            HttpPost httpPost = new HttpPost(URL);
            CloseableHttpClient client = HttpClients.createDefault();
            // 请求参数转JOSN字符串
            StringEntity entity = new StringEntity(param.toString());
            //        entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            long startTime = System.currentTimeMillis();
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            long costTime = System.currentTimeMillis() - startTime;
            LOG.warn("single costTime:" + costTime);
            result.put("costTime", costTime);
//            if (statusCode == 200) {
//                String output = EntityUtils.toString(response.getEntity(), "UTF-8");
//                LOG.warn("output: " + output);
//                result = JSONObject.parseObject(output);
//                result.put(STATUSCODE, 200);
//                result.put(REQUESTIME, System.currentTimeMillis());
//            } else {
//                result.put(STATUSCODE, statusCode);
//            }
        } catch (Exception e) {
            LOG.error("PostRequest excep: " + e.getMessage());
            result.put(STATUSCODE, -999);
        }
        return result;
    }
}
